package com.es.config;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;

@Configuration
public class RedisConfig {
	
	/**
	 * 分布式连接池
	 * @return
	 */
	@Bean(name="productShardPool")
	public ShardedJedisPool productPool(){
		JedisPoolConfig config = setConfig();
		List<JedisShardInfo> list = new ArrayList<JedisShardInfo>();
		list.add(new JedisShardInfo("192.168.0.58",7001));
		/*list.add(new JedisShardInfo("192.168.0.53",7002));
		list.add(new JedisShardInfo("192.168.0.53",7003));
		list.add(new JedisShardInfo("192.168.0.53",7004));
		list.add(new JedisShardInfo("192.168.0.53",7005));
		list.add(new JedisShardInfo("192.168.0.53",7006));*/
		//分布式多机使用
		ShardedJedisPool pool = new ShardedJedisPool(config, list, Hashing.MURMUR_HASH, ShardedJedis.DEFAULT_KEY_TAG_PATTERN);
		return pool;
	
	}
	
	
	/**
	 * 主从连接池
	 * @return
	 */
	//@Bean(name="productPool")
	public JedisSentinelPool userPool(){
		JedisPoolConfig config = setConfig();
		Set<String> sentinels = new HashSet<String>();
		sentinels.add("192.168.0.53:26380");
		sentinels.add("192.168.0.53:26381");
		String master = "mymaster";
		JedisSentinelPool pool = setSentinelPool(master, config, sentinels);
		//高可用分片集群
		return pool;
	
	}
	
	
	private JedisSentinelPool setSentinelPool(String master, JedisPoolConfig config,Set<String> sentinels) {
		//单机使用
		JedisSentinelPool pool = new JedisSentinelPool(master, sentinels,config);
		return pool;
	}
	private JedisPoolConfig setConfig() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(1000);//最大实例数
		config.setMinIdle(10);//最大空闲实例数
		config.setMinIdle(1);//最小空闲实例数
		config.setMaxWaitMillis(30000);//获取实例等待时间
		config.setTestOnBorrow(true);//获取实例时，校验对象有效，无效则重新选择
		config.setTestOnReturn(true);//归还给连接池时，校验对象有效性
		config.setTestWhileIdle(true);//是否对空闲实例校验有效性，TimeBetweenEvictionRunsMillis为正数是有效
		config.setTimeBetweenEvictionRunsMillis(1);
		return config;
	}
}
